﻿@using ExcellentCRM.DataService.Models
@using Webdiyer.WebControls.Mvc
@model ExcellentCRM.Site.Models.SearchAcctModel
@{
    ViewBag.Title = "帐号管理";
}
<style type="text/css">
    #mainContain {
        margin-top: 30px;
    }
    #AcctType {
        width: 180px;
    }
    .modal-body {
        max-height: 450px;
    }
    #acctModal {
        width: 700px;
    }
    .table th, .table td.text-center {
        text-align: center;
    }
</style>
<div id="mainContain" class="container-fluid">
    <div class="row-fluid">
        <div class="well">
            @using (Html.BeginForm("Manage", "Account", FormMethod.Post, new {@class = "form-horizontal clearfix"}))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary()
                <div class="span6">
                    <div class="control-group">
                        <label for="AcctName" class="control-label">帐号</label>
                        <div class="controls">
                            @Html.TextBoxFor(m => m.AcctName, null, new {placeholder = "帐号"})
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="AcctType">用户类型</label>
                        <div class="controls">
                            @{
                                var acctTypeDic = Account.AccountTypeDic.Where(p => p.Key != AccountType.None);
                                var acctTypeSelectList = new SelectList(acctTypeDic, "Key", "Value");
                            }
                            @Html.DropDownListFor(m => m.AcctType, acctTypeSelectList, "选择", new {tabindex = 1, @class = "span6"})
                        </div>
                    </div>
                </div>
                <div class="span5">
                    <input type="submit" value="查询" class="btn btn-primary btn-large"/>
                    <a href="@Url.Action("CreateOrUpdate", "Account")" data-backdrop="static"
                       data-keyboard="false"
                       data-target="#acctModal" data-toggle="modal" id="btnAddAcct" class="btn btn-large">
                        新增帐号
                    </a>
                </div>
            }
        </div>
    </div>
    <div class="row-fluid">
        <table id="tbAccounts" class="table table-striped table-hover table-bordered">
            <thead>
                <tr>
                    <th>帐号</th>
                    <th>帐号类型</th>
                    <th>所属部门</th>
                    <th>姓名</th>
                    <th>电话</th>
                    <th>Email</th>
                    <th>帐号状态</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @if (Model != null && Model.SearchResult != null)
                {
                    foreach (var acct in (Model.SearchResult))
                    {
                        var staff = acct.Staff.FirstOrDefault();
                        var stuClient = acct.StuClients.FirstOrDefault();
                        string nameStr =
                            acct.AcctType == AccountType.Staff && staff != null ?
                                staff.StaffName :
                                (acct.AcctType == AccountType.Student && stuClient != null
                                     ? stuClient.StudentInfo.StuName : string.Empty);
                        string phoneStr =
                            acct.AcctType == AccountType.Staff && staff != null ?
                                staff.Phone :
                                (acct.AcctType == AccountType.Student && stuClient != null ?
                                     (stuClient.StudentInfo.Phone ?? stuClient.StudentInfo.CellPhone) : string.Empty);
                        string emailStr =
                            acct.AcctType == AccountType.Staff && staff != null ?
                                staff.Email :
                                (acct.AcctType == AccountType.Student && stuClient != null ? stuClient.StudentInfo.Email : string.Empty);
                        <tr>
                            <td>@acct.AcctName</td>
                            <td>@(Account.AccountTypeDic[acct.AcctType])</td>
                            <td>@(acct.AcctType == AccountType.Staff && staff != null ? staff.Department.DeptName : string.Empty)</td>
                            <td>
                                @nameStr
                            </td>
                            <td>
                                @phoneStr
                            </td>
                            <td>
                                @emailStr
                            </td>
                            <td>
                                @(acct.StatusToken != 0 ? "有效" : "无效")
                            </td>
                            <td class="text-center">
                                <a href="@Url.Action("CreateOrUpdate", "Account", new { acctId = acct.Id })"
                                   data-backdrop="static" data-keyboard="false"
                                   data-target="#acctModal" data-toggle="modal" class="btn btn-info btn-small">
                                    编辑
                                </a>
                                <a href="@Url.Action("Delete", "Account", new { acctId = acct.Id })"
                                   class="btn btn-danger btn-small" data-bind="click: removeItem">
                                    删除
                                </a>
                            </td>
                        </tr>
                    }
                }
            </tbody>
        </table>
        @if (Model != null)
        {
            @Html.Pager(Model.SearchResult, new PagerOptions
                {
                    PageIndexParameterName = "pageIndex",
                    CurrentPagerItemWrapperFormatString = "<span class=\"cpb\">{0}</span>",
                    NumericPagerItemWrapperFormatString = "<span class=\"item\">{0}</span>",
                    CssClass = "pages",
                    SeparatorHtml = ""
                })
        }
    </div>
</div>
<div id="acctModal" class="modal hide fade" tabindex="-1" data-backdrop="true"
     role="dialog" aria-labelledby="acctModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="acctModalLabel">新增帐号</h3>
    </div>
    <div class="modal-body">
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" data-bind="click: saveHandle">保存</button>
        <button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/placeholder")
    @Scripts.Render("~/bundles/dropkick")
    @Scripts.Render("~/bundles/knockout")

    <script type="text/javascript">
        $(function() {
            $('select').dropkick();
            ko.applyBindings(new AcctModalModel(), $('#acctModal')[0]);
            ko.applyBindings(new ViewModel(), $('#mainContain')[0]);
            $(document).on('click', 'a[data-toggle="modal"]', function (ev) {
                var $lk = $(this),
                    targetId = $lk.attr('data-target'),
                    remoteUrl = $lk.attr('href'),
                    backdrop = $lk.attr('data-backdrop'),
                    keyboard = $lk.attr('data-keyboard'),
                    $modal = $(targetId),
                    $modalHeader = $modal.find('.modal-header h3'),
                    $modalBody = $modal.find('.modal-body');
                if ($modalBody.html() == '') return true;
                $modalHeader.html($lk.html());
                $modalBody.load(remoteUrl, function (resp, status) {
                    if (status === 'error')
                        $modalBody.html('发生错误，请联系管理员');
                    return this;
                });
            });
        });

        function AcctModalModel() {
            var self = this;
            self.saveHandle = function() {
                $('#acctSaveForm input[type=submit]').trigger('click');
            };
        }

        function ViewModel() {
            var self = this;
            self.removeItem = function (data, e) {
                if (!e || (!e.target && !e.srcElement) ||
                    !window.confirm('是否确认删除该帐号?')) return false;
                
                var $lk = $(e.target || e.srcElement),
                    url = $lk.attr('href');
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    success: function(result) {
                        if (!result) {
                            alert('删除失败');
                            return;
                        }
                        if (!result.success && result.message) {
                            alert(result.message);
                            return;
                        }
                        if (result.success) {
                            $lk.closest('tr').fadeOut('slow', function() {
                                $lk.closest('tr').remove();
                            });
                        }
                    }
                });
            };
        }
        
        ko.bindingHandlers.fadeVisible = {
            init: function (element, valueAccessor) {
                var value = valueAccessor();
                $(element).toggle(ko.utils.unwrapObservable(value));
            },
            update: function (element, valueAccessor) {
                var value = valueAccessor();
                ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
            }
        };
    </script>
}
